<template>
    <div>
        <div id="main" style="width:500px;height:400px;"></div>
        {{ list1 }}

    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts';
//搜索用的
const socket = ref<WebSocket | null>(null);
const list1 = ref([])

const datalist = ref([])
const valuelist = ref([])


const initecharts = () => {

    var chartDom = document.getElementById('main');
    var myChart = echarts.init(chartDom);
    var option;

    option = {
        xAxis: {
            type: 'category',
            data: datalist.value
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: valuelist.value,
                type: 'bar'
            }
        ]
    };

    option && myChart.setOption(option);
}

const initwesockt = () => {
    socket.value = new WebSocket("ws://localhost:8000/room/1/");

    // 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
    socket.value.onopen = (event) => {
        console.log("连接成功")
    }

    // 回调函数，客户端接收服务端消息
    socket.value.onmessage = (event) => {
        // {"datalist":['草药','鲜花','苹果'],"valuelist":[20,40,80]}
        list1.value = JSON.parse(event.data)
        const vdata = JSON.parse(event.data)
        datalist.value = vdata['datalist']
        valuelist.value = vdata['valuelist']
        // list1.value.push(JSON.parse(event.data))
        initecharts()
    }

    // // 当断开连接时，触发该函数
    // this.socket.onclose =function (event){
    // let tag = document.createElement("div");
    // tag.innerText = "[连接断开]";
    // document.getElementById("message").appendChild(tag);
    // }


}

onMounted(() => {
    initwesockt()
})
</script>